package com.example.service.impl;

import com.example.domain.pojo.Order;
import com.example.mapper.IOrderMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author ljs
 * @date 2025/7/16
 */
@Component
@Slf4j
public class OrderConsumer {

    @Autowired
    private IOrderMapper orderMapper;

//    @RabbitHandler
    @RabbitListener(queues = "order.queue")
    public void process(Order order, Channel channel, Message message) throws IOException {
        try {
            log.info("消费者接受: " + order);
            // 业务处理逻辑
            handleOrder(order);

            // 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 消息重试处理
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    private void handleOrder(Order order) {
        // 实际业务处理
        orderMapper.addOrder(order);
    }


}
